package com.qisu.socket.server;

import java.util.HashMap;

import org.springframework.stereotype.Component;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.ChannelHandlerContext;

/**
 * Channel repository
 *
 * @author alsan
 *
 */
@Component
public class ChannelList {
	private Log log = LogFactory.get();
	private HashMap<String, ChannelHandlerContext> cache = new HashMap<String, ChannelHandlerContext>();


	public ChannelList put(String key, ChannelHandlerContext value) {
		if(!cache.containsKey(key)) {
			cache.put(key, value);
			log.debug(key + " added to channel list");
		} else {
			ChannelHandlerContext oldChannel = cache.get(key);
			
			if(!oldChannel.equals(value)) {
				oldChannel.close();
				cache.put(key, value);
				log.debug(key + " added to channel list");
			}
			
		}
		
		log.debug("channelKey = {}", key);
		
//		try {
//			_log.debug("cache = " + _mapper.writeValueAsString(_cache));
//		} catch (JsonProcessingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		return this;
	}

	public ChannelHandlerContext get(String key) {
		if(cache.containsKey(key)) {
			return cache.get(key);
		}
		return null;
	}

	public void remove(String key) {
		if(cache.containsKey(key)) {
			cache.remove(key);
			log.debug(key + " removed from channel list");
		}
	}

	public void remove(ChannelHandlerContext ctx) {
		for(String key : cache.keySet()) {
			if(cache.get(key).equals(ctx)) {
				cache.remove(key);
				log.debug(key + " removed from channel list");

				break;
			}
		}
	}

	public int size() {
		return cache.size();
	}

	
	
}
